package www.whqgdx.tangsenling.pingdingshan;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

    private Button btnFill;
    private Button btnFillPrimarySchool;
    private Button btnIncrease;
    private Button btnDecrease;
    private Button btnIncreaseWell;
    private Switch mSwitchHeightWeight;
    private Switch mSwitchEye;
    private CheckBox cbSelectAll;
    private CheckBox cbLung;
    private CheckBox cbFifty;
    private CheckBox cbJump;
    private CheckBox cbReach;
    private CheckBox cbEightHundred;
    private CheckBox cbOneThousand;
    private CheckBox cbSitUp;
    private CheckBox cbPullUp;
    private boolean isFillHeightWeight = false;
    private boolean isFillEye = false;
    private boolean isModifyAll = true;
    private boolean isModifyLung = true;
    private boolean isModifyFifty = true;
    private boolean isModifyJump = true;
    private boolean isModifyReach = true;
    private boolean isModifyEightHundred = true;
    private boolean isModifyOneThousand = true;
    private boolean isModifySitUp = true;
    private boolean isModifyPullUp = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnFill = findViewById(R.id.btn_fill);
        btnFill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fill();
            }
        });
        btnFillPrimarySchool = findViewById(R.id.btn_fill_primary);
        btnFillPrimarySchool.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fillPrimarySchool();
            }
        });
        btnIncrease = findViewById(R.id.btn_increase_rate);
        btnIncrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                increase(true);
            }
        });
        btnDecrease = findViewById(R.id.btn_decrease_rate);
        btnDecrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                increase(false);
            }
        });
        btnIncreaseWell = findViewById(R.id.btn_increase_well_rate);
        btnIncreaseWell.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                increaseWell();
            }
        });
        mSwitchHeightWeight = findViewById(R.id.switch_weight_height);
        mSwitchHeightWeight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isFillHeightWeight = isChecked;
            }
        });
        mSwitchEye = findViewById(R.id.switch_eye);
        mSwitchEye.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isFillEye = isChecked;
            }
        });
        cbSelectAll = findViewById(R.id.cb_select_all);
        cbLung = findViewById(R.id.cb_lung);
        cbFifty = findViewById(R.id.cb_fifty);
        cbJump = findViewById(R.id.cb_jump);
        cbReach = findViewById(R.id.cb_reach);
        cbEightHundred = findViewById(R.id.cb_eight_thundred);
        cbOneThousand = findViewById(R.id.cb_one_thousand);
        cbSitUp = findViewById(R.id.cb_sit_up);
        cbPullUp = findViewById(R.id.cb_pull_up);
        cbSelectAll.setOnCheckedChangeListener(this);
        cbLung.setOnCheckedChangeListener(this);
        cbFifty.setOnCheckedChangeListener(this);
        cbJump.setOnCheckedChangeListener(this);
        cbReach.setOnCheckedChangeListener(this);
        cbEightHundred.setOnCheckedChangeListener(this);
        cbOneThousand.setOnCheckedChangeListener(this);
        cbSitUp.setOnCheckedChangeListener(this);
        cbPullUp.setOnCheckedChangeListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                        .READ_EXTERNAL_STORAGE)) {
                    Toast.makeText(this, "request read external storage", Toast.LENGTH_LONG).show();
                }
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission
                                .WRITE_EXTERNAL_STORAGE}, 9527);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 9527 && grantResults.length > 0 && grantResults[0] == PackageManager
                .PERMISSION_GRANTED) {
            Toast.makeText(this, "permission OK", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show();
        }
    }

    private void increase(final boolean isIncrease) {
        if (!isModifyAll && isSelectNone()) {
            Toast.makeText(this, "请选择要调整的项目", Toast.LENGTH_SHORT).show();
            return;
        }
        btnIncrease.setEnabled(false);
        btnDecrease.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = new File(Environment.getExternalStoragePublicDirectory("Alarms").getAbsolutePath());
                if (!dir.exists()) {
                    boolean b = dir.mkdirs();
                    if (!b) {
                        LogUtils.i("目录创建成功");
                    } else {
                        LogUtils.i("目录创建失败");
                    }
                }
                File file = new File(dir, "miaoshan.xls");
                if (file.exists()) {
                    if (isIncrease) {
                        LogUtils.i("上调及格率中");
                        TextUtils.increaseRate(file, isModifyLung, isModifyFifty, isModifyJump, isModifyReach,
                                isModifyEightHundred, isModifyOneThousand, isModifySitUp, isModifyPullUp);
                    } else {
                        LogUtils.i("下调及格率中");
                        TextUtils.decreaseRate(file, isModifyLung, isModifyFifty, isModifyJump, isModifyReach,
                                isModifyEightHundred, isModifyOneThousand, isModifySitUp, isModifyPullUp);
                    }
                } else {
                    LogUtils.i("文件不存在");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnIncrease.setEnabled(true);
                        btnDecrease.setEnabled(true);
                        if (isIncrease) {
                            Toast.makeText(MainActivity.this, "上调及格率完毕", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(MainActivity.this, "下调及格率完毕", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }).start();
    }

    private void fillPrimarySchool() {
        btnFillPrimarySchool.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = new File(Environment.getExternalStoragePublicDirectory("Alarms").getAbsolutePath());
                if (!dir.exists()) {
                    boolean b = dir.mkdirs();
                    if (!b) {
                        LogUtils.i("目录创建成功");
                    } else {
                        LogUtils.i("目录创建失败");
                    }
                }
                File file = new File(dir, "miaoshan.xls");
                if (file.exists()) {
                    TextUtils.fillPrimaryDataToExcel(file, isFillHeightWeight, true, true, true, true, true,
                            true, true);
                } else {
                    LogUtils.i("文件不存在");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnFillPrimarySchool.setEnabled(true);
                        Toast.makeText(MainActivity.this, "填充完毕", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    private void fill() {
        btnFill.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = new File(Environment.getExternalStoragePublicDirectory("Alarms").getAbsolutePath());
                if (!dir.exists()) {
                    boolean b = dir.mkdirs();
                    if (!b) {
                        LogUtils.i("目录创建成功");
                    } else {
                        LogUtils.i("目录创建失败");
                    }
                }
                File file = new File(dir, "miaoshan.xls");
                if (file.exists()) {
                    TextUtils.fillDataToExcel(file, isFillHeightWeight, isModifyLung, isModifyFifty,
                            isModifyJump, isModifyReach, isModifyEightHundred, isModifyOneThousand,
                            isModifySitUp, isModifyPullUp, isFillEye);
                } else {
                    LogUtils.i("文件不存在");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnFill.setEnabled(true);
                        Toast.makeText(MainActivity.this, "填充完毕", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    private void increaseWell() {
        if (!isModifyAll && isSelectNone()) {
            Toast.makeText(this, "请选择要调整的项目", Toast.LENGTH_SHORT).show();
            return;
        }
        btnIncreaseWell.setEnabled(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = new File(Environment.getExternalStoragePublicDirectory("Alarms").getAbsolutePath());
                if (!dir.exists()) {
                    boolean b = dir.mkdirs();
                    if (!b) {
                        LogUtils.i("目录创建成功");
                    } else {
                        LogUtils.i("目录创建失败");
                    }
                }
                File file = new File(dir, "miaoshan.xls");
                if (file.exists()) {
                    LogUtils.i("上调良好率中");
                    TextUtils.increaseWellRate(file, isModifyLung, isModifyFifty, isModifyJump, isModifyReach,
                            isModifyEightHundred, isModifyOneThousand, isModifySitUp, isModifyPullUp);
                } else {
                    LogUtils.i("文件不存在");
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btnIncreaseWell.setEnabled(true);
                        Toast.makeText(MainActivity.this, "上调良好率完毕", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_select_all:
                isModifyAll = isChecked;
                cbLung.setChecked(isModifyAll);
                cbFifty.setChecked(isModifyAll);
                cbJump.setChecked(isModifyAll);
                cbReach.setChecked(isModifyAll);
                cbEightHundred.setChecked(isModifyAll);
                cbOneThousand.setChecked(isModifyAll);
                cbSitUp.setChecked(isModifyAll);
                cbPullUp.setChecked(isModifyAll);
                break;
            case R.id.cb_lung:
                isModifyLung = isChecked;
                break;
            case R.id.cb_fifty:
                isModifyFifty = isChecked;
                break;
            case R.id.cb_jump:
                isModifyJump = isChecked;
                break;
            case R.id.cb_reach:
                isModifyReach = isChecked;
                break;
            case R.id.cb_eight_thundred:
                isModifyEightHundred = isChecked;
                break;
            case R.id.cb_one_thousand:
                isModifyOneThousand = isChecked;
                break;
            case R.id.cb_sit_up:
                isModifySitUp = isChecked;
                break;
            case R.id.cb_pull_up:
                isModifyPullUp = isChecked;
                break;
        }
    }

    public boolean isSelectNone() {
        return !isModifyLung && !isModifyFifty && !isModifyJump && !isModifyReach &&
                !isModifyEightHundred && !isModifyOneThousand && !isModifySitUp && !isModifyPullUp;
    }

    public void txtTransformExcel(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    excel();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, "解析完成", Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtils.i("解析失败1：" + e.getMessage());
                } catch (WriteException e) {
                    e.printStackTrace();
                    LogUtils.i("解析失败2：" + e.getMessage());
                }
            }
        }).start();
    }

    @RequiresApi(api = Build.VERSION_CODES.FROYO)
    private void excel() throws IOException, WriteException {
        File dir = new File(Environment.getExternalStoragePublicDirectory("Alarms").getAbsolutePath());
        if (!dir.exists()) {
            boolean b = dir.mkdirs();
            if (!b) {
                LogUtils.i("目录创建成功");
            } else {
                LogUtils.i("目录创建失败");
            }
        }
        File file = new File(dir, "test.txt");
        String fileName = dir.getAbsolutePath() + File.separator + "card_list.xls";
        File excelFile = new File(fileName);
        if (excelFile.exists()) {
            excelFile.delete();
        }
        excelFile.createNewFile();
        WritableWorkbook book = Workbook.createWorkbook(excelFile);
        WritableSheet sheet = book.createSheet("刷卡名单", 0);
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
        BufferedReader br = new BufferedReader(isr);
        String line;
        int i = 0;
        while ((line = br.readLine()) != null) {
            String[] split = line.split(",");
            if (split == null || split.length < 6) {
                continue;
            }
            //列，行，内容
            Label label1 = new Label(0, i, split[1]);
            Label label2 = new Label(1, i, split[2]);
            Label label3 = new Label(2, i, split[3]);
            Label label5 = new Label(3, i, split[5]);
            sheet.addCell(label1);
            sheet.addCell(label2);
            sheet.addCell(label3);
            sheet.addCell(label5);
            i++;
        }
        book.write();
        book.close();
    }
}
